#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Zoo on 2017/8/23

from PIL import Image
import sys,os

class size:
    def __init__(self, width=0, height=0, name='', alpha = True):
        self.width = width
        self.height = height
        self.name = name
        self.alpha = alpha
        pass
    pass

ai201x  = size(20,20,'20x20@1x')
ai202x  = size(40,40,'20x20@2x')
ai203x  = size(60,60,'20x20@3x')

ai291x  = size(29,29,'29x29@1x')
ai292x  = size(58,58,'29x29@2x')
ai293x  = size(87,87,'29x29@3x')

ai401x  = size(40,40,'40x40@1x')
ai402x  = size(80,80,'40x40@2x')
ai403x  = size(120,120,'40x40@3x')

ai571x  = size(57,57,'57x57@1x')
ai572x  = size(114,114,'57x57@2x')

ai602x  = size(120,120,'60x60@2x')
ai603x  = size(180,180,'60x60@3x')

ai721x  = size(72,72,'72x72@1x')
ai722x  = size(144,144,'72x72@2x')

ai761x  = size(76,76,'76x76@1x')
ai762x  = size(152,152,'76x76@2x')

ai501x  = size(50,50,'50x50@1x')
ai502x  = size(100,100,'50x50@2x')

ai83_5_2x   = size(167,167,'83.5@2x')

iTunes1x = size(512,512,'iTunes@1x')
iTunes2x = size(1024,1024,'iTunes@2x')
iTunes3x = size(1536,1536,'iTunes@3x')
iTunes2x_noalpha = size(1024,1024,'iTunes-noalpha@2x', False)

iconSizes = [ai201x,ai202x,ai203x,
             ai291x,ai292x,ai293x,
             ai401x,ai402x,ai403x,
             ai571x,ai572x,
             ai602x,ai603x,
             ai721x,ai722x,
             ai761x,ai762x,
             ai501x,ai502x,
             ai83_5_2x,
             iTunes1x,iTunes2x,iTunes3x,
             iTunes2x_noalpha,]

appName = 'Icon-app-'
suffix_png  = '.png'
suffix_jpg  = '.jpg'


def cover(path, local=''):
    readPath = path
    if len(local) == 0 :
        local = os.path.abspath('./')
    localPath = os.path.join(local, 'icons')
    if not os.path.exists(localPath):
        print 'should create', localPath
        os.mkdir(localPath)
        pass
    if path[0] == '.':
        readPath = os.path.join(os.path.abspath('./'), path)
        pass
    print 'reading', readPath
    img = Image.open(readPath)
    width,height = img.size
    if width < 1536 or height < 1536:
        print '\033[33msource image resolution should be 1536x1536 will work well\033[0m'
    for each in iconSizes:
        print 'resizing',each.name
        out = img.resize((each.width,each.height),Image.ANTIALIAS)
        if each.alpha is False:
            alphaImage = out.convert('RGBA')
            blendImage = Image.new('RGBA', alphaImage.size, (255,255,255,1))
            out = Image.blend(blendImage, alphaImage, 1.0)
            pass
        out.save(os.path.join(localPath, appName + each.name + suffix_png), "PNG")
        pass
    pass

if __name__ == '__main__':
    if len(sys.argv) == 2:
        cover(sys.argv[1])
    elif len(sys.argv) == 3:
        cover(sys.argv[1], sys.argv[2])
    else:
        print 'usage: make-ios-icons "file path" [output path]'
    pass